package Duration知识;

import java.time.Duration;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;

public class DurationExample {

    public static void main(String[] args) {
        // 创建开始和结束时间
        LocalDateTime start = LocalDateTime.of(2024, 11, 20, 14, 30, 0);
        LocalDateTime end = LocalDateTime.of(2024, 11, 21, 16, 45, 15);

        // 使用Duration.between计算时间差
        Duration duration = Duration.between(start, end);

        // 输出时间差的各个单位值
        System.out.println("相差的天数: " + duration.toDays());
        System.out.println("相差的小时: " + duration.toHours());
        System.out.println("相差的分钟: " + duration.toMinutes());
        System.out.println("相差的秒数: " + duration.getSeconds());
        System.out.println("相差的毫秒: " + duration.toMillis());
        System.out.println("相差的纳秒: " + duration.toNanos());

        // Duration 的其他方法
        System.out.println("是否为负数: " + duration.isNegative());
        System.out.println("相差时间的绝对值（纳秒）: " + duration.abs().toNanos());
        System.out.println("Duration转换为字符串: " + duration.toString());

        // 使用ChronoUnit直接计算差值
        System.out.println("相差的天数 (ChronoUnit): " + ChronoUnit.DAYS.between(start, end));
        System.out.println("相差的小时 (ChronoUnit): " + ChronoUnit.HOURS.between(start, end));
        System.out.println("相差的分钟 (ChronoUnit): " + ChronoUnit.MINUTES.between(start, end));
    }
}
